package com.hhj.demo.templateCode;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by KING on 2018/7/22.
 */
@Component
@Getter
@Setter
public class StudentServiceImpl implements StudentService, InitializingBean {


    @Override
    public List<Student> getAll() {
        return null;
    }

    @Override
    public Student findById(int id) {
        System.out.println("StudentServiceImpl---findById()");
        //?表示一个参数的占位符
        String sql = "select t.* from STUDENT t where t.id=?";
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet res = null;
        try {
            conn = JDBCUtil.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, id);
            res = stmt.executeQuery();
            Student stu = null;
            if (res.next()) {
                stu = new Student();
                stu.setId(res.getInt("id"));
                stu.setAge(res.getInt("age"));
                stu.setName(res.getString("name"));
            }
            return stu;
        } catch (Exception err) {
            System.out.println(err);

        } finally {
            try {
                if (res != null) {
                    res.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqlEx2) {

            }
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化StudentServiceImpl---afterPropertiesSet");
    }
}
